﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Vds2465Telegrams;

namespace Vds2465Parser
{
    internal static class GenParse_UserData_20_State
    {
        #region private constants

        private const int NrOfBytes = 7;

        #endregion private constants

        #region internal methods

        internal static byte[] GenerateBytes(UserData userData)
        {
			byte[] userDataBytes = GenParse_UserData_Report.GenerateBytes(userData, NrOfBytes, UserData.UserData20State);
			return userDataBytes;
        }

        internal static bool ParseBytes(byte[] userDataBytes, out UserData userData20, out int consumedBytes)
        {
			// set default values
			userData20 = null;
			consumedBytes = 0;

			byte device;
			byte address;
			byte addressAddOn;
			eAddressExtension_1 addressExtension;
			ReportType_Base reportTypeBase;
			bool bRetVal = GenParse_UserData_Report.ParseBytes(userDataBytes, NrOfBytes, UserData.UserData20State,
						out device, out address, out addressAddOn, out addressExtension, out reportTypeBase);
			if (bRetVal)
			{
				// now do further check, is this scenario AddressExtension = Input or Output?
				if (
						(addressExtension == eAddressExtension_1.Input)
					||	(addressExtension == eAddressExtension_1.Output)
					)
				{
					eAddressExtension_1_InputOutput addressExtension_1_InputOutput = addressExtension == eAddressExtension_1.Input ? 
												eAddressExtension_1_InputOutput.Input : eAddressExtension_1_InputOutput.Output;
					userData20 = new UserData_20_State(device, address, addressAddOn, addressExtension_1_InputOutput, reportTypeBase);
					consumedBytes = NrOfBytes;
					return true;
				}
				
				if (addressExtension == eAddressExtension_1.Disruption)
				{
					// Disruption scenario
					eDisruptionCode disruptionCode;
					bRetVal = GenParse_DisruptionCode.ParseByte(address, out disruptionCode);
					if (bRetVal)
					{
						userData20 = new UserData_20_State(device, disruptionCode, addressAddOn, reportTypeBase);
						consumedBytes = NrOfBytes;
						return true;
					}

					// TODO handle error (unknown disruptionCode Byte)
					return false;
				}

				// TODO handle error (unknown addressExtension)
				return false;
			}

			// TODO handle error (not enough bytes)
			return false;
        }

        #endregion internal methods
    }
}
